package com.denlaku.longan.service.impl;

import com.denlaku.longan.repository.LexiconItemRepository;
import com.denlaku.longan.service.DictionaryService;
import com.denlaku.longan.service.LexiconItemService;
import com.denlaku.longan.vo.LexiconItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tianx
 */
@Service
public class LexiconItemServiceImpl implements LexiconItemService {
    @Autowired
    private LexiconItemRepository lexiconItemRepository;

    @Autowired
    private DictionaryService dictionaryService;

    /**
     * 添加词条
     *
     * @param lexiconItem 参数
     * @return 添加行数
     */
    @Override
    public int add(LexiconItem lexiconItem) {
        String text = lexiconItem.getText();
        if (StringUtils.isEmpty(text)) {
            return 0;
        }
        lexiconItem.setText(text.trim());
        LexiconItem old = this.get(lexiconItem);
        if (old != null) {
            return 0;
        }
        int add = lexiconItemRepository.add(lexiconItem);
        Long tenantId = lexiconItem.getTenantId();
        List<LexiconItem> wordItems = listByTenantId(tenantId);
        dictionaryService.loadLexiconItems(String.valueOf(tenantId), wordItems);
        return add;
    }

    /**
     * 删除词条
     *
     * @param lexiconItem 参数
     * @return 删除行数
     */
    @Override
    public int delete(LexiconItem lexiconItem) {
        return lexiconItemRepository.delete(lexiconItem);
    }

    /**
     * 获取词条
     *
     * @param query 参数
     * @return 词条
     */
    @Override
    public LexiconItem get(LexiconItem query) {
        return lexiconItemRepository.get(query);
    }

    /**
     * 查询词条列表
     *
     * @param query 查询参数
     * @return list
     */
    @Override
    public List<LexiconItem> list(LexiconItem query) {
        return lexiconItemRepository.list(query);
    }

    /**
     * 查询词条列表
     *
     * @param tenantId 组合ID
     * @return list
     */
    @Override
    public List<LexiconItem> listByTenantId(Long tenantId) {
        LexiconItem query = new LexiconItem();
        query.setTenantId(tenantId);
        return this.list(query);
    }

}
